package com.zys.sac.core.helper;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 内存token持久化处理器，将token持久化至内存中，该bean已经通过plugin模块默认注入
 *
 * Created by zhongjunkai on 2022/4/13.
 */
public class InMemoryTokenManager implements TokenManager {

    // todo 这个地方后面可以实现自己的本地缓存
    protected TimedCache<String, UserDetails> tokenCache;

    protected long expiredTime;

    public InMemoryTokenManager(long expiredTime) {
        this.expiredTime = expiredTime;
        tokenCache = CacheUtil.newTimedCache(this.expiredTime);
        //10秒钟定时清理过期缓存
        tokenCache.schedulePrune(10000);
    }

    @Override
    public String createAndSaveToken(UserDetails userDetails) {
        return this.createAndSaveToken(userDetails, this.expiredTime);
    }

    @Override
    public String createAndSaveToken(UserDetails userDetails, long expired) {
        String token = generateToken(userDetails);
        String cacheKey = token;
        tokenCache.put(cacheKey, userDetails, expired);
        return token;
    }

    @Override
    public void renewalToken(String token) {
        this.renewalToken(token, this.expiredTime);
    }

    @Override
    public void renewalToken(String token, long expired) {
        String cacheKey = token;
        UserDetails userDetails = tokenCache.get(cacheKey);
        tokenCache.put(cacheKey, userDetails, expired);
    }

    @Override
    public UserDetails getUserDetails(String token) {
        String cacheKey = token;
        return tokenCache.get(cacheKey);
    }

    @Override
    public void invalidToken(String token) {
        String cacheKey = token;
        tokenCache.remove(cacheKey);
    }

}
